/**
 * 
 */
package com.amoby.main.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.amoby.main.entity.Area;
import com.amoby.main.mapper.AreaMapper;
import com.amoby.main.service.AreaService;

/**
 * @Copyright: 本内容仅限于重庆爱赢科技有限公司内部使用，禁止转发.
 * @Author: daijiangguo 2015年1月19日 上午9:30:25
 * @Version: $Id$
 * @Desc: <p>
 *        </p>
 */
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaMapper           areaMapper;

    public List<Map<String, Object>> getAllAreas() {
        return areaMapper.getAllAreas();
    }

    public int updateArea(Area area) {
        if (StringUtils.isBlank(area.getCode())) {
            List<String> list = areaMapper.queryUserCodes(area.getParentId());
            String prentCode = "";
            if (area.getParentId() != 0) {
                Area parent = areaMapper.selectByPrimaryKey(area.getParentId());
                prentCode = parent.getCode();
            }
            for (int i = 1; i < 1000; i++) {
                String tempCode = (1000 + i + "").substring(1);
                if (!list.contains(tempCode)) {
                    area.setCode(prentCode + tempCode);
                    break;
                }
            }
        }
        return areaMapper.updateByPrimaryKeySelective(area);
    }

    public int insertArea(Area area) {
        if (StringUtils.isBlank(area.getCode())) {
            List<String> list = areaMapper.queryUserCodes(area.getParentId());
            String prentCode = "";
            if (area.getParentId() != 0) {
                Area parent = areaMapper.selectByPrimaryKey(area.getParentId());
                prentCode = parent.getCode();
            }
            for (int i = 1; i < 1000; i++) {
                String tempCode = (1000 + i + "").substring(1);
                if (!list.contains(tempCode)) {
                    area.setCode(prentCode + tempCode);
                    break;
                }
            }
        }
        int i = areaMapper.insertSelective(area);
        return i;
    }

    public int deleteArea(Integer menuId) {
        return areaMapper.deleteByAreaId(menuId, menuId);
    }

    @Override
    public List<Map<String, Object>> queryParent() {
        return areaMapper.queryParent();
    }

    @Override
    public List<Map<String, Object>> queryByParentId(Long parentId) {
        return areaMapper.queryByParentId(parentId);
    }

    @Override
    public int checkDelArea(String code, Long parentId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("parentId", parentId);
        map.put("code", code);
        return areaMapper.checkDelArea(map);
    }
}
